package com.telit.firecommand.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.telit.common.util.RedisUtils;
import com.telit.firecommand.constant.RedisKeyConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @Auther zhouyu
 * @description 业务处理(用于保存每台设备z值)
 **/
public class ClientHandler extends SimpleChannelInboundHandler {

    private static ChannelHandlerContext ctx;

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {
        ClientHandler.ctx = channelHandlerContext;
        System.out.println("hp platform has connected....");
        super.channelActive(channelHandlerContext);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause){
        cause.printStackTrace();
        channelHandlerContext.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0,bytes);
            String receiveMsg=new String(bytes, StandardCharsets.UTF_8);
            String[] infos = receiveMsg.split("\r\n");
            //解析报文存储到缓存用于监控推送火情时进行ptz控制
            Arrays.stream(infos).forEach(e->{
                JSONObject jsonObject = JSON.parseObject(e);
                JSONObject param = jsonObject.getJSONObject("param");
                String ip = param.getString("ip");
                BigDecimal z = param.getBigDecimal("z");
                RedisUtils.setBoundHash(RedisKeyConstant.CAMERA_DEVICE,ip,z.toPlainString());
            });
        } catch (Exception ignore) {
            //解析失败不做处理
        }
    }

    /**
     * 发送报文给和普威视平台（ptz控制）
     * @param message 消息报文
     */
    public static void ptzCamera(String message){
        Channel channel = ClientHandler.ctx.channel();
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        try {
            //发送队列低于高水位才执行write
            if (channel.isActive() && channel.isWritable()) {
                ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);
                channel.writeAndFlush(byteBuf);
            }
        } catch (Exception e) {
            //发送失败不做处理,防止线程阻塞
        }
    }
}

